<template>
  <div>
    <!-- 导入对话框 -->
    <ElementDialog :title="title" :visible.sync="upload.open" width="400px">
      <ElRow>
        <ElCol :span="24">
          <div class="block">
            <span>所属年月</span>
            <ElDatePicker v-model="year_month" type="month" value-format="yyyy-MM" placeholder="选择月" />
          </div>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="24">
          <ElUpload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="headers"
            :action="url + year_month"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip text-center">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <ElLink
                  v-if="tempUrl"
                  type="primary"
                  :underline="false"
                  style="font-size: 12px; vertical-align: baseline"
                  @click="downExcelTemp">
                  下载模板
                </ElLink>
              </div>
            </template>
          </ElUpload>
        </ElCol>
      </ElRow>
      <template #footer>
        <div class="dialog-footer">
          <ElButton type="primary" @click="submitFileForm">确 定</ElButton>
          <ElButton @click="upload.open = false">取 消</ElButton>
        </div>
      </template>
    </ElementDialog>
    <!--校验失败错误数据-->
    <ElementDialog title="校验失败数据" :visible.sync="errorVisible">
      <ElTable :data="errorData">
        <ElTableColumn property="lineNum" label="行号" width="50" />
        <ElTableColumn property="errors" label="错误描述" show-overflow-tooltip>
          <template #default="scope">
            <ElTag v-for="error in scope.row.errors" :key="error" type="danger">
              {{ error }}
            </ElTag>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElementDialog>
  </div>
</template>

<script>
  import { getToken } from '@/util/auth'
  import { mapState } from 'vuex'

  export default {
    name: 'ExcelUpload',
    components: {},
    props: {
      url: {
        type: String
      },
      title: {
        type: String
      },
      tempUrl: {
        type: String
      },
      tempName: {
        type: String
      }
    },
    data() {
      return {
        upload: {
          open: false,
          isUploading: false
        },
        errorVisible: false,
        errorData: [],
        year_month: `${new Date().getFullYear()}-${new Date().getMonth() + 1}`
      }
    },
    computed: {
      ...mapState('user', ['sysUser']),
      headers() {
        const tenantId = this.sysUser.tenantId
        return {
          Authorization: `Bearer ${getToken()}`,
          'TENANT-ID': tenantId || '1'
        }
      }
    },
    methods: {
      downExcelTemp() {
        this.$downBlobFile(this.tempUrl, {}, this.tempName === '' ? 'temp.xlsx' : this.tempName)
      },
      handleFileUploadProgress() {
        this.upload.isUploading = true
      },
      handleFileSuccess(response) {
        this.upload.isUploading = false
        this.upload.open = false
        this.$refs.upload.clearFiles()

        // 校验失败
        if (response.code === 1) {
          this.$refs.upload.clearFiles()
          let errorMsg = ''
          for (const dataKey in response.data) {
            const data = response.data[dataKey]
            errorMsg += `第${data.lineNum}行：${data.errors}\n`
          }
          this.$message.error(`导入失败，以下数据不合法:${errorMsg}`)
        } else {
          this.$message.success('导入成功')
          // 刷新表格
          this.$emit('refreshDataList')
        }

        // 校验失败
        /* if (response.code === 1) {
        this.$message.error("导入失败，以下数据不合法");

        this.errorVisible = true;
        this.errorData = response.data;
        this.$refs.upload.clearFiles();
      } else {
        this.$message.success("导入成功");
          // 刷新表格
          this.$emit("refreshDataList");
      } */
      },
      submitFileForm() {
        this.$refs.upload.submit()
      },
      show() {
        this.upload.isUploading = false
        this.upload.open = true
      }
    }
  }
</script>
